package com.onesatoshi.mm;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.onesatoshi.NetWorkStateReceiver;
import com.onesatoshi.mm.db.Chat;
import com.onesatoshi.mm.db.ChatDao;
import com.onesatoshi.mm.db.User;
import com.onesatoshi.mm.db.UserDao;
import com.onesatoshi.mm.util.AccessibilityUtil;
import com.onesatoshi.mm.util.DeviceUtil;
import com.onesatoshi.mm.util.NetStateUtils;
import com.onesatoshi.mm.util.SimplePreference;
import com.onesatoshi.mm.util.StringUtils;
import com.socks.okhttp.plus.OkHttpProxy;
import com.socks.okhttp.plus.callback.OkCallback;
import com.socks.okhttp.plus.parser.OkTextParser;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

import static com.onesatoshi.mm.Config.SERVER_URL;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public class WxRobotActivity extends AppCompatActivity {

    private CheckBox cb_assist;
    private CheckBox cb_window;

    private int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 2;

    public static final String TAG = WxRobotActivity.class.getName();

    // 监听网络变化
    NetWorkStateReceiver netWorkStateReceiver;

    @Override
    @SuppressLint("NewApi")
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // OkHttpClient 初始化网络配置
        OkHttpClient.Builder builder = OkHttpProxy.getInstance().newBuilder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS);
        OkHttpProxy.setInstance(builder.build());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            // 关闭提示框
            closeAndroidPDialog();
        }

        setContentView(R.layout.activity_main);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        RadioGroup rgroup = findViewById(R.id.radioGroup);
        rgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                              @Override

                                              public void onCheckedChanged(RadioGroup rg, int checkedId) {

                                                  if (!AccessibilityUtil.isSettingOpen(WxRobotActivity.this, WxRobotService.class)) {
//
                                                      Toast.makeText(WxRobotActivity.this, "辅助功能未开启", Toast.LENGTH_SHORT).show();

                                                      rg.setOnCheckedChangeListener(null);
                                                      rg.check(-1);
                                                      rg.setOnCheckedChangeListener(this);

                                                      return;
                                                  }

                                                  Log.i(TAG, "mask:" + Config.taskMask + ",checkedId:" + checkedId);

                                                  switch (checkedId) {

                                                      /**
                                                       * 自动抢红包
                                                       */
//                                                      case R.id.cb_lucky_money:
//                                                          Config.taskMask = Config.MASK_AUTO_OPEN_LUCKY_MONEY;
//                                                          Log.d(TAG, "自动抢红包功能，掩码设置成功");
//
//                                                          break;
//
//                                                      /**
//                                                       * 自动添加附近的人
//                                                       */
//                                                      case R.id.cb_people_nearby:
//
//                                                          Config.taskMask = Config.MASK_AUTO_ADD_NEARBY;
//                                                          Log.d(TAG, "自动添加附近的人功能，掩码设置成功");
//
//                                                          break;
//
//                                                      /**
//                                                       * 自动添加通讯录
//                                                       */
//                                                      case R.id.cb_add_phonebook:
//
//                                                          Config.taskMask = Config.MASK_AUTO_ADD_PHONEBOOK;
//                                                          Log.d(TAG, "自动添加通讯录好友功能，掩码设置成功");
//
//                                                          break;

                                                      /**
                                                       * 自动添加客户
                                                       */
//                                                      case R.id.cb_add_customer:
//
//                                                          Config.taskMask = Config.MASK_AUTO_ADD_CUSTOMER;
//
//                                                          Log.d(TAG, "自动添加客户功能，掩码设置成功");
//                                                          break;

//                                                      /**
//                                                       * 自动点赞
//                                                       */
//                                                      case R.id.cb_auto_prize:
//
//                                                          Config.taskMask = Config.MASK_AUTO_SNS_PRIZE;
//                                                          Log.d(TAG, "自动点赞功能打开了");
//
//                                                          break;
//
//
//                                                      /**
//                                                       * 添加群好友
//                                                       */
//                                                      case R.id.cb_accept_friend_add_2group:
//
//                                                          Config.taskMask = Config.MASK_AUTO_ACCEPT_FRIEND_ADD_2GROUP;
//                                                          Log.d(TAG, "添加群好友功能，掩码设置成功");
//
//                                                          break;
//
                                                      /**
                                                       * 自动发朋友圈
                                                       */
//                                                      case R.id.cb_auto_sns:
//
//                                                          Config.taskMask = Config.MASK_AUTO_POST_SNS;
//                                                          Log.d(TAG, "自动发朋友圈功能，掩码设置成功");
//
//                                                          break;
//
//                                                      /**
//                                                       * 自动回复
//                                                       */
//                                                      case R.id.cb_auto_repay:
//
//                                                          Config.taskMask = Config.MASK_AUTO_REPLY;
//                                                          Log.d(TAG, "自动回复功能，掩码设置成功");
//
//                                                          break;
//
//                                                      /**
//                                                       * 自动抓取群信息
//                                                       */
//                                                      case R.id.cb_auto_crawler:
//
//                                                          Config.taskMask = Config.MASK_AUTO_CRAWL_GROUPMSG;
//                                                          Log.d(TAG, "自动抓取群信息功能，掩码设置成功");
//
//                                                          break;
                                                  }

                                                  Log.i(TAG, "mask:" + Config.taskMask + ",checkedId:" + checkedId);
                                              }
                                          }
        );

        // 辅助功能
        cb_assist = (CheckBox) findViewById(R.id.cb_assist_permission);
        if (cb_assist != null) {
            cb_assist.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                    if (isChecked && !AccessibilityUtil.isSettingOpen(WxRobotActivity.this, WxRobotService.class)) {
                        /**
                         * 申请权限
                         */
                        AccessibilityUtil.checkSetting(WxRobotActivity.this, WxRobotService.class);

                    }
                }
            });
        }

        // 悬浮框
        cb_window = (CheckBox) findViewById(R.id.cb_show_window);
        if (cb_window != null) {
            cb_window.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (buttonView.getId() == R.id.cb_show_window) {

                        /**
                         * 展示悬浮框
                         */
                        if (isChecked) {
                            requestFloatWindowPermissionIfNeeded();

                            TasksWindow.init(getApplicationContext());
                            TasksWindow.show("一聪助手使用......");
                        } else {
                            TasksWindow.dismiss();
                        }

                    }
                }
            });
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取保存在sd中的 设备唯一标识符
                    String readDeviceID = DeviceUtil.readDeviceID(WxRobotActivity.this);

                    //获取缓存在  sharepreference 里面的 设备唯一标识
                    String string = SimplePreference.getString(SpConstant.SP_DEVICES_ID, readDeviceID, getApplicationContext());

                    //判断 app 内部是否已经缓存,  若已经缓存则使用app 缓存的 设备id
                    if (string != null) {

                        //app 缓存的和SD卡中保存的不相同 以app 保存的为准, 同时更新SD卡中保存的 唯一标识符
                        if (StringUtils.isBlank(readDeviceID) && !string.equals(readDeviceID)) {

                            // 取有效地 app缓存 进行更新操作
                            if (StringUtils.isBlank(readDeviceID) && !StringUtils.isBlank(string)) {
                                readDeviceID = string;
                                DeviceUtil.saveDeviceID(readDeviceID, WxRobotActivity.this);
                            }
                        }
                    }

                    // app 没有缓存 (这种情况只会发生在第一次启动的时候)
                    if (StringUtils.isBlank(readDeviceID)) {

                        //保存设备id
                        readDeviceID = DeviceUtil.getDeviceId(WxRobotActivity.this);
                    }

                    //左后再次更新app 的缓存
                    SimplePreference.putString(SpConstant.SP_DEVICES_ID, readDeviceID, getApplicationContext());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        TextView deviceView = findViewById(R.id.deviceId);
        deviceView.setText(SimplePreference.getString(SpConstant.SP_DEVICES_ID, DeviceUtil.getDeviceId(getApplicationContext()), getApplicationContext()));

//        Bugly.init(getApplicationContext(), "dd89cee0f6", false);


        // 默认选中
        cb_window.setChecked(true);

        Button updateBtn = findViewById(R.id.updateBtn);
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new UpdateAppManager
//                        .Builder()
//                        //当前Activity
//                        .setActivity(this)
//                        //更新地址
//                        .setUpdateUrl(mUpdateUrl)
//                        //实现httpManager接口的对象
//                        .setHttpManager(new UpdateAppHttpUtil())
//                        .build()
//                        .update();
            }
        });


        // 刷新数据
        pushInfo();

//        CommonUtil.printAllApp(getApplicationContext());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_REQUEST_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
            } else {
                // Permission Denied
            }
        }
    }

    @Override
    protected void onResume() {
        //  注册网络监听器
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        Log.i(TAG, "注册网络监听器");

        // 设置选中状态
        cb_assist.setChecked(AccessibilityUtil.isSettingOpen(WxRobotActivity.this, WxRobotService.class));

        // 悬浮框
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            cb_window.setChecked(Settings.canDrawOverlays(this));

            if (!Settings.canDrawOverlays(this)) {
                requestFloatWindowPermissionIfNeeded();
            }
        }

        super.onResume();
    }

    //onPause()方法注销
    @Override
    protected void onPause() {
        unregisterReceiver(netWorkStateReceiver);

        Log.i(TAG, "pause暂停");
        super.onPause();
    }

    /**
     * 刷新数据
     */
    private void pushInfo() {

        final Handler updateUserStatusHandler = new Handler();
        Runnable updateUserStatusRunnable = new Runnable() {
            @Override
            public void run() {

                // 检查网络连接
//                Log.d(TAG, "网络连接类型：" + NetStateUtils.getConnectedType(getApplicationContext()));
                if (!NetStateUtils.isNetworkConnected(getApplicationContext())) {
                    Log.e(TAG, "网络连接异常, " + NetStateUtils.getConnectedType(getApplicationContext()));

                } else {
                    final UserDao userDao = new UserDao(getApplicationContext());
                    List<User> userList = userDao.findAllToDelete();

                    for (int i = 0; i < userList.size(); i++) {
                        final User u = userList.get(i);
                        postUsers(u);
                    }
                }

                updateUserStatusHandler.postDelayed(this, Config.PUSH_RUNNABLE_PERIOD);

                Log.i(TAG, "推送任务，定时检查是否需要更新加人状态");
            }
        };
        updateUserStatusHandler.postDelayed(updateUserStatusRunnable, Config.RUNNABLE_DELAY);


        final Handler pushChatHandler = new Handler();
        Runnable pushChatRunnable = new Runnable() {
            @Override
            public void run() {

                // 检查网络连接
//                Log.d(TAG, "网络连接类型：" + NetStateUtils.getConnectedType(getApplicationContext()));
                if (!NetStateUtils.isNetworkConnected(getApplicationContext())) {
                    Log.e(TAG, "网络连接异常, " + NetStateUtils.getConnectedType(getApplicationContext()));

                } else {
                    final ChatDao chatDao = new ChatDao(getApplicationContext());
                    List<Chat> chatList = chatDao.findAllToDelete();
                    for (Chat chat : chatList) {
                        postChat(chat);
                    }
                }

                pushChatHandler.postDelayed(this, Config.PUSH_RUNNABLE_PERIOD);

                Log.i(TAG, "推送任务，定时检查是否添加聊天记录");
            }
        };
        pushChatHandler.postDelayed(pushChatRunnable, Config.RUNNABLE_DELAY);

    }


    // 推送聊天记录
    public static final String URL_CHAT = SERVER_URL + "/chat/add";

    public void postChat(final Chat chat) {

        OkHttpProxy
                .post()
                .url(URL_CHAT)
                .tag(this)
                .addParams("nickname", chat.getNickname() == null || "".equals(chat.getNickname()) ? "0" : chat.getNickname())
                .addParams("wxid", chat.getWxid() == null || "".equals(chat.getWxid()) ? "0" : chat.getWxid())
                .addParams("type", chat.getType() == null || "".equals(chat.getType()) ? "0" : chat.getType())
                .addParams("deviceid", chat.getDeviceid() == null || "".equals(chat.getDeviceid()) ? "0" : chat.getDeviceid())
                .addParams("content", chat.getContent() == null || "".equals(chat.getContent()) ? "0" : chat.getContent())
                .addHeader("header", "okhttp")
                .enqueue(new OkCallback<String>(new OkTextParser() {
                }) {
                    @Override
                    public void onSuccess(int code, String msg) {

                        Log.i(TAG, "添加聊天记录，msg:" + msg);
                        if ("success".equals(msg)) {
                            ChatDao chatDao = new ChatDao(getApplicationContext());
                            chatDao.del(chat.getId());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        Log.e(TAG, "添加聊天记录，请求失败");

                        e.printStackTrace();
                    }
                });
    }

    // 推送用户状态更新
    private static String URL_USERS = SERVER_URL + "/wx/update";

    public void postUsers(final User user) {

        OkHttpProxy
                .post()
                .url(URL_USERS)
                .tag(this)
                .addParams("phone", user.getPhone())
                .addParams("nickname", StringUtils.isBlank(user.getNickname()) ? "" : user.getNickname())
                .addParams("status", StringUtils.isBlank(user.getStatus()) ? "" : user.getStatus())
                .addParams("wxid", StringUtils.isBlank(user.getWxid()) ? "" : user.getWxid())
                .addHeader("header", "okhttp")
                .enqueue(new OkCallback<String>(new OkTextParser() {
                }) {
                    @Override
                    public void onSuccess(int code, String msg) {

                        Log.i(TAG, "更新加人状态，msg:" + msg);
                        if ("success".equals(msg)) {
                            UserDao userDao = new UserDao(getApplicationContext());
                            userDao.del(user.getId());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        Log.e(TAG, "更新加人状态，请求失败");

                        e.printStackTrace();
                    }
                });
    }

    /**
     * 申请悬浮窗权限
     */
    private void requestFloatWindowPermissionIfNeeded() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {

            new AlertDialog.Builder(this)
                    .setMessage(R.string.dialog_enable_overlay_window_msg)
                    .setPositiveButton(R.string.dialog_enable_overlay_window_positive_btn
                            , new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    dialog.dismiss();

                                    // 打开权限设置窗口
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                                    intent.setData(Uri.parse("package:" + getPackageName()));

                                    startActivity(intent);
                                }
                            })

                    .setNegativeButton(android.R.string.cancel
                            , new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    cb_window.setChecked(false);
                                }
                            })

                    .create()
                    .show();

        }
    }

    /**
     * 在MIUI 10升级到 Android P 后 每次进入程序都会弹一个提醒弹窗
     * 去掉在Android P上的提醒弹窗 （Detected problems with API compatibility(visit g.co/dev/appcompat for more info)
     */
    private void closeAndroidPDialog() {
        try {

            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);

            declaredConstructor.setAccessible(true);

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Class cls = Class.forName("android.app.ActivityThread");
            Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");

            declaredMethod.setAccessible(true);
            Object activityThread = declaredMethod.invoke(null);

            Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
